<template>
    <div class="container" @click="handleWrapperClick">
        <headerView :headerTitle="headerTitle" class="header" />
        <div class="FileUpload" ref="FileUpload">
            <div class="directory-header">
                <div class="left">
                    <el-icon @click.prevent="backParent()">
                        <ArrowLeft />
                    </el-icon>
                </div>
                <div class="right" @click.stop="togglePopup($event)">
                    <el-icon>
                        <MoreFilled />
                    </el-icon>
                    <teleport to="body">
                        <div class="popup" v-if="isPopupVisible">
                            <div>
                                <p @click.stop="toUploadRight()">上传文件</p>
                            </div>
                            <div>
                                <p @click.stop="showAddDirectory">新建文件夹</p>
                            </div>
                        </div>
                    </teleport>
                </div>
            </div>
            <div v-if="textData">{{ textData }}</div>
            <div v-if="!textData" class="directory-content">
                <div class="directory-item" v-for="(item, index) in tabItems" :key="index"
                    @click.stop="currentItem(item)" @touchstart="gtouchstart(item, index)" @touchmove="gtouchmove(item)"
                    @touchend="gtouchend(item)" :id="index">
                    <div class="content-icon">
                        <div v-if="isPicture(item)" class="demo-image__preview">
                            <el-image style="width: 30px;height: 30px;" :src="item.url" :zoom-rate="1.2" :max-scale="7"
                                :min-scale="0.2" ref="previewImg" fit="cover" />
                        </div>
                        <img v-if="!isPicture(item)" :src="getIcon(item.extName)" alt=""></img>
                    </div>
                    <div class="content">
                        <div class="content-left">
                            <div class="content-name">{{ item.name }}</div>
                            <div class="content-date">
                                <p>{{ item.date }}
                                    <span v-if="item.extName == '' || item.extName == null">
                                        -{{ item.childsNum }}项
                                    </span>
                                </p>
                            </div>
                        </div>
                        <div>
                            <el-icon>
                                <ArrowRight />
                            </el-icon>
                        </div>
                    </div>
                    <div class="operate" v-if="isIndex == index" ref="Operate">
                        <div v-if="item.extName == '' || item.extName == null">
                            <p @click.stop="toUpload(item.id)">上传文件</p>
                        </div>
                        <div v-if="item.extName == '' || item.extName == null">
                            <p @click.stop="showAddDirectory(item.id)"> 新建文件夹</p>
                        </div>
                        <div v-if="item.childsNum <= 0 || item.extName == null">
                            <p @click.stop="deleteDirectory(item)">删除</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <readPicture v-if="showImageViewer" v-model:showImageViewer="showImageViewer" :urls="urls"
            :currentIndex="currentIndex" />
    </div>
</template>

<script setup name="FileUpload">
import { ref, onMounted, watch, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import headerView from '@/components/Header/index.vue';
import service from '@/utils/request';
import getIcon from '@/components/Function/GetIcon';
import readPicture from '../HomeView/readPicture.vue';
import { ElMessage } from 'element-plus';
const headerTitle = ref({
    title: '上传',
    aline: 'left',
});
const router = useRouter();
const showImageViewer = ref(false);
const FileUpload = ref(null);
const Operate = ref(null);
const isPopupVisible = ref(false);
const isIndex = ref();
const parentIds = ref([]);
const tabItems = ref([]);
const toUpload = (id) => {
    router.push({
        name: 'Upload',
        params: { parentId: id },
    });
};
const initTable = (id, extName) => {
    if (id <= 0 || id == undefined || id == null) {
        id = 0;
    }
    // 如果是文件夹，则获取文件夹列表；如果是文件，则获取文件，查看文件的内容。
    // extName 为空时，获取文件夹列表；extName 不为空时，获取文件列内容。
    if (extName == 0 || extName == '' || extName == undefined || extName == null) {
        service({
            url: 'api/FileDirectorys?parentId=' + id,
            method: 'get',
        }).then((res) => {
            if (res != undefined) {
                tabItems.value = [];
                Array.from(res.data).forEach((item) => {
                    if (item.extName == '.jpg' || item.extName == '.png' || item.extName == '.jpeg' || item.extName == '.gif' || item.extName == '.bmp') {
                        tabItems.value.push({
                            id: item.id, name: item.name, date: item.createTime, childsNum: item.childsNum, extName: item.extName,
                            parentId: item.parentId, url: 'http://localhost:5198/api/FileInfos/' + item.id,
                        });
                    } else {
                        tabItems.value.push({
                            id: item.id, name: item.name, date: item.createTime, childsNum: item.childsNum, extName: item.extName,
                            parentId: item.parentId, url: '',
                        });
                    }
                });
            }
        });
    }
};
const urls = ref([]);
const currentIndex = ref(0);
const isPicture = (item) => {
    if (item.extName == '.jpg' || item.extName == '.png' || item.extName == '.jpeg' || item.extName == '.gif' || item.extName == '.bmp'
        && item.url != '') {
        return true;
    } else {
        return false;
    }
}
const currentItem = (item) => {
    if (item.extName == '' || item.extName == undefined || item.extName == null) {
        parentIds.value.push(item.id);
        initTable(item.id, item.extName);
    } else if (item.extName == '.jpg' || item.extName == '.png' || item.extName == '.jpeg' || item.extName == '.gif' || item.extName == '.bmp') {
        urls.value = [item.url];
        currentIndex.value = 0;
        showImageViewer.value = true;
    } else {
        ElMessage({
            message: '暂不支持预览文件',
            type: 'warning',
            plain: true,
        });
    }
};
const backParent = () => {
    parentIds.value.pop();
    initTable(parentIds.value[parentIds.value.length - 1], 0, '');
};
const showAddDirectory = (parentId) => {
    isPopupVisible.value = false;
    document.querySelector('.right').style.color = '#000';

    ElMessageBox.prompt('请命名文件夹名称', '新建文件夹', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        showClose: false,
        closeOnClickModal: false,
        inputPattern: /^[\u4E00-\u9FA5A-Za-z0-9-_]+$/,
        inputErrorMessage: '文件夹名称由中文、英文、数字包括下-和_组成',
    }).then(({ value }) => {
        // newDirectory.value = value;
        if (value) {
            console.log(parentId);
            addDirectory(parentId, value);
            isIndex.value = null;
        }
    }).catch(() => { isIndex.value = null; });
};
const addDirectory = (parentId, directoryName) => {
    if (typeof parentId != "number") {
        if (parentIds.value.length <= 0) {
            parentId = 0;
        } else {
            parentId = parentIds.value[parentIds.value.length - 1];
        }
    }
    service({
        url: 'api/FileDirectorys',
        method: 'post',
        data: {
            parentId: parentId,
            directoryName: directoryName,
            directoryPath: "str",
            createTime: '2024-12-6',
            creator: 0,
        },
    }).then((res) => {
        if (res.status == 200) {
            initTable(parentId, '');
        }
    });
};
const togglePopup = (event) => {
    isPopupVisible.value = !isPopupVisible.value;
    if (isPopupVisible.value) {
        document.querySelector('.right').style.color = '#d19792';
    } else {
        document.querySelector('.right').style.color = '#000';
    }
};
const handleWrapperClick = () => {
    if (isPopupVisible.value) {
        togglePopup();
    }
    isIndex.value = null;
};
const gtouchstart = (item, index) => {
    item.timeOutEvent = setTimeout(() => {
        isIndex.value = index;
    }, 800);
    return false;
};
const gtouchmove = (item) => {
    clearTimeout(item.timeOutEvent);
    item.timeOutEvent = 0;
};
const gtouchend = (item) => {
    clearTimeout(item.timeOutEvent);
    return false;
};
watch(isIndex, (newValue) => {
    if (newValue) {
        nextTick(() => {
            if (FileUpload.value && Operate.value) {
                const parentHeight = FileUpload.value.clientHeight;
                const operateHeight = Operate.value[0].clientHeight;
                const operatePosition = parseInt(Operate.value[0].getBoundingClientRect().top);
                if (parentHeight <= operateHeight + operatePosition + 20) {
                    console.log('超出');
                    // 需要算出卷曲在顶部里面去的高度，然后加上这个卷曲的高度。
                    Operate.value[0].style.top = -(operateHeight + operatePosition - parentHeight + 80) + 'px';
                }
            }
        });
    }
});
const deleteDirectory = (item) => {
    if (item.extName == '' || item.extName == undefined || item.extName == null) {
        service({
            url: 'api/FileDirectorys/' + item.id,
            method: 'delete',
        }).then((res) => {
            if (res.status == 200) {
                ElMessage({
                    message: res.data + ':' + item.name,
                    type: 'success',
                    plain: true,
                });
                initTable(parentIds.value[parentIds.value.length - 1], '');
            }
        });
    } else {
        service({
            url: 'api/FileInfos/' + item.id,
            method: 'delete',
        }).then((res) => {
            if (res.status == 200) {
                ElMessage({
                    message: res.data + ':' + item.name,
                    type: 'success',
                    plain: true,
                });
                initTable(parentIds.value[parentIds.value.length - 1], '');
            }
        });
    }
    isIndex.value = null;
};
const toUploadRight = () => {
    if (parentIds.value.length >= 1) {
        toUpload(parentIds.value[parentIds.value.length - 1]);
    } else {
        toUpload(0);
    }
}
onMounted(() => {
    initTable();
});
</script>

<style scoped>
.popup {
    position: fixed;
    top: 90px;
    right: 5px;
    background-color: #444;
    border-radius: 3px;
    width: 100px;
    padding: 10px;
    color: white;
    z-index: 1000;
    opacity: 0.9;
}

.popup p {
    margin: 5px 3px;
    padding: 5px 0px;
    border-bottom: #fbc6c6 1px solid;
}

.wrapper {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;
}

.container {
    widows: 100vw;
    /* height: calc(100vh-60px); */
    height: 100%;
    margin: 0;
    padding: 0;
}

.header {
    width: 100vw;
    height: 60px;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1000;
}

.FileUpload {
    width: 100%;
    height: 100%;
}

.directory-header {
    margin: 0 auto;
    margin-top: 60px;
    width: 95%;
    height: 40px;
    line-height: 55px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
    overflow: hidden;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.directory-content {
    margin: 0 auto;
    flex: 1;
    width: 95%;
    border: 1px solid transparent;
}

.directory-breadcrumb {
    float: left;
}

.breadcrumb-name {
    height: 100%;
    margin: 0;
    float: left;
}

.directory-icon {
    height: 100%;
    margin: 0 1px;
    float: left;
}

.directory-item {
    width: 100%;
    height: 55px;
    margin-top: 5px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
}

.content-icon {
    width: 40px;
    height: 55px;
    text-align: center;
    line-height: 55px;
}

.content-icon>img {
    width: 30px;
    height: 30px;
}

.content {
    width: 85%;
    height: 100%;
    padding-left: 5px;
    margin: 0 auto;
    padding: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #999999;
}

.content-left {
    margin: 0;
    padding: 0;
    height: 40px;
}

.content-name {
    margin: 0;
    padding: 0;
    height: 24px;
    line-height: 24px;
    font-size: 14px;
}

.content-date {
    margin: 0;
    padding: 0;
    height: 40%;
}

.content-date>p,
.content-date>p>span {
    margin: 0;
    padding: 0;
    height: 100%;
    font-size: 13px;
    color: #999999;
}

.operate {
    position: absolute;
    top: 0;
    left: 40%;
    width: 100px;
    padding: 10px;
    background-color: #444;
    border-radius: 3px;
    opacity: 0.9;
    color: white;
    z-index: 1000;
}

.operate p {
    margin: 5px 3px;
    padding: 5px 0px;
    border-bottom: #fbc6c6 1px solid;
}
</style>